// pages/volunteer/index/index.js
import requestUtil from "../../../api/request"
import API from "../../../api/http.api"
const app = getApp()
const openId = app.globalData.openId
// 录音管理器
const recorderManager = wx.getRecorderManager()
// 声音播放管理器
const audioPlayer = wx.createInnerAudioContext();

Page({

  /**
   * // 注意 fileProp (chat，appointment)
   */

  /**
   * 页面的初始数据
   */
  data: {
    triggered: false,
    // 是否有正在进行的预约
    hasProcessingAppointment: false,
    is_recording: false,
    // 是否播放的是聊天音频
    isPlayingMsg: false,
    // 是否播放的是预约音频
    isPlayingAppointment: false,
    // 该请求的页面
    nextPage: 1,
    // 一页的条数
    pageSize: 30,
    // 是否显示遮罩
    showCancelSendRecord: false,
    // 下方按钮的文字
    sendMsgBtnTextRecord: "按住说话",
    // 提示文字
    cancelTipTextRecord: "滑动到此处松手取消发送",
    // 音频的时长
    audioLengthRecord: 0,
    // 是否发送消息
    ifSendMsgRecord: false,
    processingAppointment: {},
    chatMsgList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.hasOpenDeviceAuthorizeModal = false

    console.log("v-onLoad-------------------------------onShow")

    this.setData({
      height: wx.getSystemInfoSync().windowHeight,
      userInfo: app.globalData.userInfo
    })

    // 监听声音播放
    audioPlayer.onPlay(() => {
      console.log("播放开始")
      // 两种情况
      if (this.data.isPlayingAppointment == true) {
        // 情况一正在播放的是预约音频
        console.log("播放预约音频")
        // 用来跳过第一次
        var i = 0
        var processingAppointment = this.data.processingAppointment
        // 获取当前播放音频的总时长
        var duration = Math.ceil(processingAppointment.duration / 1000)
        // 获取播放到的位置，调整进度条
        this.data.audioPercentageInterval = setInterval(() => {

          var currentTime = audioPlayer.currentTime
          if (i > 0) {
            // 计算进度条的值
            processingAppointment.audioPercentage = Math.ceil(100 * currentTime / duration)

            // 计算 showTime1
            currentTime = Math.ceil(currentTime)
            var min = parseInt(currentTime / 60);
            var sec = parseInt(currentTime % 60);
            if (min.toString().length == 1) {
              min = `0${min}`;
            }
            if (sec.toString().length == 1) {
              sec = `0${sec}`;
            }
            processingAppointment.showTime1 = `${min}:${sec}`
            console.log(processingAppointment.showTime1)
            this.setData({
              processingAppointment: processingAppointment
            })
          }
          i = i + 1
        }, 1000);
      } else {
        // 情况二，正在播放的是聊天消息
        console.log("播放聊天音频")
      }
    })

    // 调用 audioPlayer.stop() 后触发 
    audioPlayer.onStop(() => {
      console.log("播放结束")

      // 清除正在播放音频的计时器，由于回调函数的延时执行，为避免出现bug，应在stop后立即清除计时器
      // clearInterval(this.data.audioPercentageInterval)
      // console.log(this.data.isPlayingAppointment)
      // console.log(this.data.isPlayingMsg)

      // if (this.data.isPlayingAppointment == true) {
      //   // 卡片上的预约音频
      //   var processingAppointment = this.data.processingAppointment
      //   // 重置播放状态，如果是拖动后的stop则不重置
      //   if (this.data.isSlider == true) {
      //     this.data.isSlider = false
      //   }
      // }
    })

    // 自然播放完后触发
    audioPlayer.onEnded(() => {
      console.log("自然播放结束")
      // 清除计时器
      clearInterval(this.data.audioPercentageInterval)

      if (this.data.isPlayingAppointment == true) {
        // 卡片上的预约音频
        console.log("预约音频自然播放结束")
        // 重置刚刚播放完的音频
        var processingAppointment = this.data.processingAppointment
        // 重置播放状态
        processingAppointment.playing = false
        // 重置时间进度
        processingAppointment.showTime1 = "00:00"
        this.setData({
          isPlayingAppointment: false,
          processingAppointment: processingAppointment
        })
      } else if (this.data.isPlayingMsg == true) {
        if (this.data.isPlayingMsg == true) {
          console.log("聊天音频自然播放结束")
          // 聊天音频
          var list = this.data.chatMsgList
          for (let index = 0; index < list.length; index++) {
            list[index].playing = false
          }
          this.data.isPlayingMsg = false,
            this.setData({
              chatMsgList: list
            })
        } else {
          console.log("自然播放结束")
        }
      }
    })

    audioPlayer.onError((error) => {
      console.log(error)
    })

    // 录音开始
    recorderManager.onStart((res) => {
      console.log("录音开始")
    })

    // 录音结束
    recorderManager.onStop((res) => {
      console.log("录音结束")
      console.log(res)
      var duration = res.duration
      var that = this

      this.setData({
        showCancelSendRecord: false,
        sendMsgBtnTextRecord: "按住说话",
        audioLengthRecord: 0,
        cancelTipTextRecord: "滑动到此处松手取消发送"
      })
      clearInterval(this.data.audioPercentageInterval)

      if (this.data.ifSendMsgRecord == false) {
        console.log("已取消发送")
        return
      }

      if (duration < 1500) {
        console.log("录音时间太短")
        wx.showToast({
          title: '录音时间太短',
          icon: 'none',
          duration: 2000
        })
      }

      //上传录制的音频
      wx.uploadFile({
        header: API.REQUEST_HEADER,
        url: API.FILE_UPLOAD,
        filePath: res.tempFilePath,
        name: 'file',
        formData: {
          fileProp: API.fILE_PROP_CHAT
        },
        success: function(res) {
          let result = JSON.parse(res.data)
          console.log(result)

          let id = app.globalData.openId + API.SEPARATOR + Date.now()
          if (result.code == 20000) {
            requestUtil.post(API.SEND_CHAT_MSG, {
              "id": id,
              "createTime": new Date().format(),
              "msgType": "audio",
              "content": result.data.fileName,
              "duration": Math.ceil(duration),
              "fromUserOpenId": app.globalData.openId,
              "toUserOpenId": that.data.processingAppointment.fromUserOpenId,
              "appointmentId": that.data.processingAppointment.id,
            }).then(res => {
              var list = that.data.chatMsgList;
              list.push({
                "side": 'right',
                "msgLength": Math.floor(duration / 1000),
                "playing": false,
                "id": id,
                "createTime": new Date().format(),
                "msgType": "audio",
                "content": API.FILE_DOWNLOAD + "?fileName=" + result.data.fileName + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_CHAT,
                "duration": Math.ceil(duration),
                "fromUserOpenId": app.globalData.openId,
                "toUserOpenId": that.data.processingAppointment.fromUserOpenId,
                "appointmentId": that.data.processingAppointment.id,
              })
              console.log(list)
              that.setData({
                toMsgIndex: 'msg' + String(list.length - 1),
                chatMsgList: list
              })

            }).catch(err => {
              console.log(err)
              wx.showToast({
                title: "发送失败",
                icon: 'none',
                duration: 2000
              })
            })

          } else {
            wx.showToast({
              title: "发送失败",
              icon: 'none',
              mask: true,
              duration: 2000
            })
          }
        },
        fail: function(res) {
          console.log(res)
          wx.showToast({
            title: "发送失败",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("v-index-------------------------------onShow")
    // 权限检查
    this.checkAllDeviceAuthorize()

    this.checkProcessingAppointment()
  },

  // 检查是否有正在进行的预约
  checkProcessingAppointment: function() {
    var that = this
    requestUtil.post(API.PROCESSING_APPOINTMENT_V, {
        'userType': app.globalData.userType
      })
      .then(res => {
        console.log(res)
        var data = res.data
        data["content"] = API.FILE_DOWNLOAD + "?fileName=" + data["content"] + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_APPOINTMENT
        data["playing"] = false
        data["showTime1"] = "00:00"
        var duration = Math.ceil(data.duration / 1000)
        var min = parseInt(duration / 60);
        var sec = parseInt(duration % 60);
        if (min.toString().length == 1) {
          min = `0${min}`;
        }
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        data["showTime2"] = `${min}:${sec}`
        that.data.nextPage = 1
        that.setData({
          // nextPage: 1,
          processingAppointment: data,
          hasProcessingAppointment: true,
        })
        that.loadMsg()
        app.globalData.disableHell = true
      }).catch((err) => {
        app.globalData.disableHell = false
        that.setData({
          hasProcessingAppointment: false
        })
      })
  },

  // 完成预约
  complete: function(e) {
    audioPlayer.stop()
    var that = this
    var key = e.target.dataset.key
    wx.showModal({
      title: '提示',
      content: '您确定您已完成了此次预约?若遇特殊情况无法完成请先与您帮助的人沟通',
      // showCancel: false,
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          requestUtil.post(API.COMPLETE_APPOINTMENT, {
            appointmentId: key
          }).then(res => {
            app.globalData.disableHell = false
            audioPlayer.stop()
            clearInterval(that.data.audioPercentageInterval)
            that.setData({
              triggered: false,
              hasProcessingAppointment: false,
              is_recording: false,
              isPlayingMsg: false,
              isPlayingAppointment: false,
              nextPage: 1,
              pageSize: 10,
              showCancelSendRecord: false,
              sendMsgBtnTextRecord: "按住说话",
              cancelTipTextRecord: "滑动到此处松手取消发送",
              audioLengthRecord: 0,
              ifSendMsgRecord: false,
              processingAppointment: {},
              chatMsgList: []
            })
            console.log(res)
          }).catch(e => {
            console.log(e)
          })
        }
      }
    })
  },

  /**
   * 卡片上的播放/暂停按钮
   */
  playAudio: function() {
    var processingAppointment = this.data.processingAppointment

    console.log(audioPlayer.paused)

    // 停止当前播放
    if (this.data.isPlayingAppointment) {
      console.log("停止正在播放的预约音频")
      audioPlayer.stop()
    } else if (this.data.isPlayingMsg) {
      console.log("停止正在播放的聊天音频")
      this.playMsg()
    }
    clearInterval(this.data.audioPercentageInterval)


    // 如果播放的就是预约音频则暂停
    if (processingAppointment.playing) {
      processingAppointment.playing = false
      this.setData({
        isPlayingAppointment: false,
        processingAppointment: processingAppointment
      })
      return
    }

    processingAppointment.playing = true
    console.log(processingAppointment.content)
    audioPlayer.src = processingAppointment.content

    this.setData({
      isPlayingAppointment: true,
      processingAppointment: processingAppointment
    })
    audioPlayer.play()
  },

  /**
   * 语音消息相关
   */
  // 播放语音
  playMsg: function(event) {
    var key = event != undefined ? event.target.dataset.key : this.playingMsgId

    console.log(audioPlayer.paused)

    // 停止当前的语音
    // if (!audioPlayer.paused) {
    //   console.log("停止当前音频")
    if (this.data.isPlayingAppointment) {
      console.log("停止正在播放的预约音频")
      this.playAudio()
    } else if (this.data.isPlayingMsg) {
      console.log("停止正在播放的聊天音频")
      audioPlayer.stop()
    }
    clearInterval(this.data.audioPercentageInterval)
    // }

    var list = this.data.chatMsgList
    var pause
    var src
    for (let index = 0; index < list.length; index++) {
      if (list[index].id != key) {
        list[index].playing = false
      } else {
        if (list[index].playing == true) {
          list[index].playing = false
          pause = true
        } else {
          list[index].playing = true
          pause = false
          src = list[index].content
        }
      }
    }

    if (pause) {
      this.setData({
        isPlayingMsg: false,
        chatMsgList: list
      })
      return
    } else {
      this.setData({
        isPlayingMsg: true,
        chatMsgList: list
      })
    }


    this.playingMsgId = key

    // 播放音频
    console.log(src)
    audioPlayer.src = src
    audioPlayer.play()
  },


  /**
   * 发送语音
   */
  // 手指按下
  handleRecordStart: function() {

    if (this.data.is_recording == false) {

      if (this.data.isPlayingAppointment) {
        console.log("停止正在播放的预约音频")
        this.playAudio()
      } else if (this.data.isPlayingMsg) {
        console.log("停止正在播放的聊天音频")
        this.playMsg()
      }
      clearInterval(this.data.audioPercentageInterval)

      this.setData({
        audioLengthRecord: 0,
        is_recording: true, // 开始录音标志
        ifSendMsgRecord: true,
        showCancelSendRecord: true,
        sendMsgBtnTextRecord: "松开发送"
      })

      recorderManager.start({
        duration: 60000,
        format: "mp3"
      })

      this.data.audioPercentageInterval = setInterval(() => {
        var audioLengthRecord = this.data.audioLengthRecord + 1
        this.setData({
          audioLengthRecord: audioLengthRecord
        })
      }, 1000)

    }
  },

  // 手指移动
  handleTouchMove: function(event) {
    // 避免频繁 setData
    if (event.touches[0].clientY <= this.data.height * 0.73 && this.data.cancelTipTextRecord != "松开 取消") {
      this.setData({
        ifSendMsgRecord: false,
        cancelTipTextRecord: "松开 取消"
      })
    } else if (event.touches[0].clientY > this.data.height * 0.73 && this.data.cancelTipTextRecord != "滑动到此处松手取消发送") {
      this.setData({
        ifSendMsgRecord: true,
        cancelTipTextRecord: "滑动到此处松手取消发送"
      })
    }
  },

  // 手指离开
  handleRecordStop: function(e) {
    if (e.touches.length == 0) {
      recorderManager.stop() //结束录音
      this.setData({
        is_recording: false
      })
    }
  },

  // 收到消息
  onMessage: function(data) {
    console.log("index 页收到如下消息")
    console.log(data)
    var msg = JSON.parse(data.data)
    if (msg.message_property == 'chat') {
      var list = this.data.chatMsgList
      msg.data.content = API.FILE_DOWNLOAD + "?fileName=" + msg.data.content + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_CHAT
      msg.data.side = 'left'
      msg.data.msgLength = Math.floor(msg.data.duration / 1000)
      msg.data.playing = false
      list.push(msg.data)
      this.setData({
        chatMsgList: list,
        toMsgIndex: 'msg' + String(list.length - 1)
      })
    }
  },

  // 加载聊天消息
  loadMsg: function() {
    var that = this;
    requestUtil.post(API.GET_CHAT_LIST, {
      'appointmentId': that.data.processingAppointment.id,
      'pageSize': this.data.pageSize,
      'currentPage': this.data.nextPage
    }).then(res => {
      console.log(res)
      var chatMsgList = that.data.chatMsgList;
      // 第一次加载重置 chatList
      if (that.data.nextPage == 1) {
        chatMsgList = []
      }
      res.data.list.forEach((value) => {
        if (value.fromUserOpenId == app.globalData.openId) {
          value.side = "right"
        } else {
          value.side = "left"
        }
        value.content = API.FILE_DOWNLOAD + "?fileName=" + value.content + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_CHAT
        value.msgLength = Math.floor(value.duration / 1000)
        value.playing = false
        chatMsgList.unshift(value)
      })
      var nextPage = this.data.nextPage + 1
      if (nextPage == 2) {
        that.setData({
          toMsgIndex: 'msg' + String(chatMsgList.length - 1),
          chatMsgList: chatMsgList,
          nextPage: nextPage,
          pageCount: res.data.pageCount,
        })
      } else {
        this._freshing = false
        that.setData({
          triggered: false,
          chatMsgList: chatMsgList,
          nextPage: nextPage,
          pageCount: res.data.pageCount,
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },

  onPulling(e) {},

  // 下拉加载
  onRefresh() {
    if (this._freshing) return
    this._freshing = true
    console.log('下拉加载。。。')
    if (this.data.nextPage <= this.data.pageCount) {
      console.log("加载更多历史消息中。。。")
      this.loadMsg()
    } else {
      this.setData({
        triggered: false,
      })
      this._freshing = false
      console.log("没有更多历史消息")
    }
  },

  onRestore(e) {},

  onAbort(e) {},

  /**
   * 检查所有权限
   */
  checkAllDeviceAuthorize: function() {
    var that = this
    wx.getSetting({
      withSubscriptions: true,
    }).then((result) => {
      console.log('getSetting', result)
      that.authorizeMic = result.authSetting['scope.record']
      that.authorizeCamera = result.authSetting['scope.camera']
      that.authorizeMainSwitch = result.subscriptionsSetting.mainSwitch
      that.authorizeSubMsg = result.subscriptionsSetting.itemSettings == undefined ? '' : result.subscriptionsSetting.itemSettings['V2N215C6c8dAg4qUxlZShk8VzxijNnRGUWop1BvB9Qo']

      if (that.authorizeMic && that.authorizeCamera && (that.authorizeMainSwitch || that.authorizeSubMsg == 'accept')) {
        console.log("已通过所有授权")
        return
      }

      that.checkMicAuthorize()

    })
  },

  /**
   * 授权麦克风
   */
  checkMicAuthorize: function() {
    var that = this
    wx.authorize({
      scope: 'scope.record',
    }).then((res) => {
      console.log('authorize mic', res)
      //   that.authorizeMic = true
      that.checkCameraAuthorize()
    }).catch((error) => {
      console.log('authorize mic error', error)
      //   that.authorizeMic = false
      if (error.errMsg == "authorize:fail auth cancel") {
        // 点击返回键取消了授权
        that.checkAllDeviceAuthorize()
      } else {
        that.openConfirm('您没有打开麦克风权限，将无法使用小程序', '去打开', 'record')
      }
    })
  },

  /**
   * 授权摄像头
   */
  checkCameraAuthorize: function() {
    var that = this
    wx.authorize({
      scope: 'scope.camera',
    }).then((res) => {
      console.log('authorize camera', res)
      //   that.authorizeCamera = true
      that.checkSubMsgAuthorize()
    }).catch((error) => {
      console.log('authorize camera error', error)
      //   that.authorizeCamera = false
      if (error.errMsg == "authorize:fail auth cancel") {
        // 点击返回键取消了授权
        that.checkCameraAuthorize()
      } else {
        that.openConfirm('您没有打开摄像头权限，将无法使用小程序', '去打开', 'camera')
      }
    })
  },

  /**
   * 检查是否订阅，勾选“总是保持以上选择，不再询问”，打开了消息推送开关
   */
  checkSubMsgAuthorize: function() {
    var that = this
    wx.getSetting({}).then((res) => {
      console.log(res)

      if (that.authorizeSubMsg == 'accept') {
        if (that.authorizeMainSwitch) {
          console.log("用户已永久授权订阅消息并打开了接收消息开关")
        } else {
          that.openConfirm('请在 设置->消息订阅 中打开接收订阅消息开关', '去打开', 'subMsg')
        }
      } else if (that.authorizeSubMsg == 'reject') {
        console.log("用户已拒绝授权订阅消息")
        that.openConfirm('请在 设置->消息订阅 中打开接收订阅消息开关，并勾选下面的相关消息', '去打开', 'subMsg')
      } else {
        console.log("用户未永久授权订阅消息")
        that.openConfirm('您需要订阅以下消息并勾选“总是保持以上选择，不再询问”才能收到即时求取消息', '确定', 'subMsg-o')
      }

    })
  },

  openConfirm: function(content, confirmText, authType) {
    var that = this
    if (this.hasOpenDeviceAuthorizeModal) {
      return
    }
    this.hasOpenDeviceAuthorizeModal = true
    return wx.showModal({
      title: '授权申请',
      content: content,
      confirmText: confirmText,
      showCancel: false,
      success: (res) => {
        this.hasOpenDeviceAuthorizeModal = false
        console.log(res)
        // 点击“确认”时打开设置页面
        if (res.confirm) {
          if (authType == 'subMsg-o') {
            wx.requestSubscribeMessage({
              tmplIds: ['V2N215C6c8dAg4qUxlZShk8VzxijNnRGUWop1BvB9Qo'],
              success(res) {}
            })
          } else {
            wx.openSetting({
              success: (res) => {},
            })
          }
        } else {
          console.log('用户点击取消')
          if (authType == 'record') {
            that.checkMicAuthorize()
          } else if (authType == 'camera') {
            that.checkCameraAuthorize()
          } else if (authType == 'subMsg' || authType == 'subMsg-o') {
            that.checkSubMsgAuthorize()
          }
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    audioPlayer.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})